package message

import (
	"context"
	"github.com/gin-gonic/gin"
	"net/http"
	"strconv"
	"userop_bff/controller"
	"userop_bff/forms"
	"userop_bff/global"
	"userop_bff/model"
	"userop_bff/userop_proto"
)

// 批量获取留言信息
func List(c *gin.Context) {
	//userId, _ := c.Get("userId")
	//userIdInt := userId.(int32)
	userId := c.Query("user_id")
	userIdInt, _ := strconv.Atoi(userId)
	list, err := global.MessageSrvClient.MessageList(context.Background(), &userop_proto.MessageRequest{UserId: int32(userIdInt)})
	if err != nil {
		controller.HandleGrpcErrorToHttp(err, c)
		return
	}
	var messageList []model.Message
	for _, v := range list.Data {
		messageList = append(messageList, model.Message{
			Id:          int(v.Id),
			UserId:      v.UserId,
			MessageType: v.MessageType,
			Subject:     v.Subject,
			Message:     v.Message,
			File:        v.File,
		})
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 0,
		"msg":  "留言列表获取成功",
		"data": map[string]interface{}{
			"total":       list.Total,
			"addressList": messageList,
		},
	})
}

// 添加留言
func Add(c *gin.Context) {
	//userId, _ := c.Get("userId")
	//userIdInt := userId.(int32)
	userId := c.PostForm("user_id")
	userIdInt, _ := strconv.Atoi(userId)
	messageForm := forms.MessageForm{}
	if err := c.ShouldBind(&messageForm); err != nil {
		controller.ReturnErrorJson(err, c)
		return
	}
	message, err := global.MessageSrvClient.CreateMessage(context.Background(), &userop_proto.MessageRequest{
		UserId:      int32(userIdInt),
		MessageType: messageForm.MessageType,
		Subject:     messageForm.Subject,
		Message:     messageForm.Message,
		File:        messageForm.File,
	})
	if err != nil {
		controller.HandleGrpcErrorToHttp(err, c)
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 0,
		"msg":  "添加留言成功",
		"data": message.Id,
	})
}
